import { create } from "zustand";
import { ConversationItem, GroupItem, GroupMemberItem } from "open-im-sdk-rn/lib/typescript/types/entity";
import OpenIMSDKRN from "open-im-sdk-rn";
import { v4 as uuidv4 } from "uuid";
import { ConversationStore, ConversationListUpdateType } from "./type";
import { conversationSort, isGroupSession } from "@/utils/ImCommon";
import { useMessageStore } from "./message";
import { useUserStore } from "./user";
import {router} from "expo-router";
import { GroupMemberRole } from "@/constants/ImContants"
import {showToast} from "@/utils/rootToast";

const CONVERSATION_SPLIT_COUNT = 10000;


export const useConversationStore = create<ConversationStore>()((set, get) => ({
    conversationIniting: true,
    conversationList: [],
    currentConversation: undefined,
    unReadCount: 0,
    currentGroupInfo: undefined,
    currentMemberInGroup: undefined,
    currentGroupList: [],
    searchMemberList: [],
    getConversationListByReq: async (isOffset?: boolean) => {
        if (!isOffset) set(() => ({ conversationIniting: true }));

        let tmpConversationList = [] as ConversationItem[];
        const noticeData = {
            attachedInfo: "",
            burnDuration: 0,
            conversationID: "si_1862328257862537217_186ass3831730563158017",
            conversationType: 99,
            draftText: "",
            draftTextTime: 0,
            ex: "",
            faceURL: "https://hd-uat-1258162617.cos.ap-guangzhou.myqcloud.com/app/1862328257862537217/upload/67b7ea9be4b0535a78d0f4e7.png",
            groupAtType: 0,
            groupID: "",
            isMsgDestruct: false,
            isNotInGroup: false,
            isPinned: false,
            isPrivateChat: false,
            latestMsg: JSON.stringify(
                `{
                  "clientMsgID": "999810d07ba01610011bfacb9893d618",
                  "serverMsgID": "b92f768aa0a200dc5add8c04658ed7fe",
                  "createTime": 1740104251596,
                  "sendTime": 1740104251741,
                  "sessionType": 1,
                  "sendID": "1863831730563158017",
                  "recvID": "1862328257862537217",
                  "msgFrom": 100,
                  "contentType": 101,
                  "senderPlatformID": 1,
                  "senderNickname": "手机用户0697你",
                  "senderFaceUrl": "https://hd-uat-1258162617.cos.ap-guangzhou.myqcloud.com/icon/default_profile.png",
                  "seq": 129,
                  "isRead": true,
                  "status": 2,
                  "textElem": { "content": "你好" },
                  "attachedInfoElem": {
                    "groupHasReadInfo": { "hasReadCount": 0, "groupMemberCount": 0 },
                    "isPrivateChat": false,
                    "burnDuration": 0,
                    "hasReadTime": 0,
                    "isEncryption": false,
                    "inEncryptStatus": false
                  }
                }`
            ),
            // latestMsgSendTime: 1740104251741,
            maxSeq: 0,
            minSeq: 0,
            msgDestructTime: 0,
            recvMsgOpt: 0,
            showName: "系统通知",
            unreadCount: 2,
            updateUnreadCountTime: 0,
            userID: "1863831730563158017",
        };
        try {
            const data = await OpenIMSDKRN.getConversationListSplit(
                {
                    offset: isOffset ? get().conversationList.length : 0,
                    count: CONVERSATION_SPLIT_COUNT,
                },
                uuidv4(),
            );
            // console.log('OpenIMSDKRN.getConversationListSplit', data);
            tmpConversationList = data;

        } catch (error) {
            // feedbackToast({ error, msg: t("toast.getConversationFailed") });
            if (!isOffset) set(() => ({ conversationIniting: false }));
            return true;
        }
        //conversationList: [...(isOffset ? [...state.conversationList] : [noticeData]), ...tmpConversationList],
        set((state) => ({
            conversationList: [...(isOffset ? [...state.conversationList] : []), ...tmpConversationList],
        }));
        if (!isOffset) set(() => ({ conversationIniting: false }));
        return tmpConversationList.length === CONVERSATION_SPLIT_COUNT;
    },
    setConversationListL: async (list: ConversationItem[]) => {
        set((state) => ({
            conversationList: [...list],
        }));
    },
    updateConversationList: async (list: ConversationItem[], type: ConversationListUpdateType) => {

        if (type === "filter") {
            const { conversationSort } = await import("@/utils/ImCommon"); // 动态导入
            set((state) => {
                const sortList = conversationSort([...list, ...state.conversationList]);
                let tmpList = [];
                sortList.forEach((item) => {
                    if (item.conversationType !== 99) {
                        tmpList.push(item);
                    } else {
                        tmpList = [item, ...tmpList];
                    };
                })
                return ({
                    conversationList: tmpList,
                })
            });
            return;
        }
        let filterArr: ConversationItem[] = [];
        const chids = list.map((ch) => ch.conversationID);
        filterArr = get().conversationList.filter((tc) => !chids.includes(tc.conversationID));

        const { conversationSort } = await import("@/utils/ImCommon"); // 动态导入
        set(() => {
            let sortList = conversationSort([...list, ...filterArr]);
            let tmpList = [];
            sortList.forEach((item) => {
                if (item.conversationType !== 99) {
                    tmpList.push(item);
                } else {
                    tmpList = [item, ...tmpList];
                };
            })

            return ({ conversationList: tmpList })
        });
    },
    updateUnReadCount: (count: number) => {
        set(() => ({ unReadCount: count }));
    },
    updateCurrentConversation: (conversation?: ConversationItem, isJump?: boolean) => {
        // console.log('updateCurrentConversation')

        if (!conversation) {
            set(() => ({
                currentConversation: undefined,
                quoteMessage: undefined,
                currentGroupInfo: undefined,
                currentMemberInGroup: undefined,
            }));
            return;
        }
        const prevConversation = get().currentConversation;

        const toggleNewConversation = conversation.conversationID !== prevConversation?.conversationID;
        if (toggleNewConversation && isGroupSession(conversation.conversationType)) {
            get().getCurrentGroupInfoByReq(conversation.groupID);
            get().getCurrentMemberInGroupByReq(conversation.groupID);
            get().getCurrentGroupMenmberInfoByReq(conversation.groupID);
            useMessageStore.getState().updateReverseLoad(false);
        }
        if (toggleNewConversation && !isJump) {
            useMessageStore.getState().updateJumpClientMsgID();
        }
        set(() => ({ currentConversation: { ...get().currentConversation, ...conversation } }));
    },
    getCurrentMemberInGroupByReq: async (groupID: string) => {
        let memberInfo: GroupMemberItem;
        const selfID = useUserStore.getState().selfInfo.userID;

        try {
            const data = await OpenIMSDKRN.getSpecifiedGroupMembersInfo(
                {
                    groupID,
                    userIDList: [selfID],
                },
                uuidv4(),
            );
            [memberInfo] = data;
        } catch (error) {
            // feedbackToast({ error, msg: t("toast.getGroupMemberFailed") });
            return;
        }
        set(() => ({ currentMemberInGroup: { ...memberInfo } }));
    },
    getCurrentGroupInfoByReq: async (groupID: string) => {
        // const dispatch = useDispatch();
        console.log('groupIDgroupIDgroupIDgroupIDgroupID', groupID);
        let groupInfo: GroupItem;
        try {
            const data = await OpenIMSDKRN.getSpecifiedGroupsInfo([groupID], uuidv4());
            [groupInfo] = data;
            console.log('getCurrentGroupInfoByReq', data);
            // const groupAdminInfo = await OpenIMSDKRN.getUsersInfo([data[0].ownerUserID], uuidv4());
            // set(() => ({ currentGroupList: [{ ...groupAdminInfo[0].publicInfo, superAdmin: 1 }, ...get().currentGroupList] }))
            set(() => ({ currentGroupInfo: { ...get().currentGroupInfo, ...groupInfo } }));
        } catch (error) {
            console.log('errorsss', error);
            // feedbackToast({ error, msg: t("toast.getGroupInfoFailed") });
            return;
        }
    },
    getCurrentGroupMenmberInfoByReq: async (groupID: string) => {
        console.log('groupID', groupID);
        let groupInfo = [];

        const params = {
            groupID: groupID,
            filter: "Nomal",
            offset: 1,
            count: 500,
        };

        console.log('params', params);
        try {
            const data = await OpenIMSDKRN.getGroupMemberList(params, uuidv4());
            console.log('datassssssss', data);
            groupInfo = [...groupInfo, ...data];
        } catch (error) {
            console.log('err',error)
            // feedbackToast({ error, msg: t("toast.getGroupInfoFailed") });
            return;
        }

        try {
            const data = await OpenIMSDKRN.getGroupMemberOwnerAndAdmin(groupID, uuidv4())
              groupInfo = [...data,...groupInfo]
        } catch (err) {
            console.log('err', err);
        };

        groupInfo.forEach((item) => {
            if (item.roleLevel == GroupMemberRole.Admin) {
                Reflect.set(item, "select", true);
            };
        })

        groupInfo.sort((a,b) => b.roleLevel - a.roleLevel );
        const uniqueArray = Array.from(new Map(groupInfo.map(item => [item.userID, item])).values());
        console.log('uniqueArray', uniqueArray);
        set(() => ({ currentGroupList: [...uniqueArray] }));
    },
    sendGroupNotice: async (noticeStr: string) => {
        const params = {
            groupID: get().currentGroupInfo.groupID,
            notification: noticeStr,
        };
        try {
            const data = await OpenIMSDKRN.setGroupInfo(params, uuidv4());
        } catch (e) {
            console.log('e', e);
        };
    },
    postDsimissGroup: () => {
        try {
            const data = OpenIMSDKRN.dismissGroup(get().currentGroupInfo.groupID, uuidv4());
            setTimeout(() => {
                get().getCurrentGroupInfoByReq(get().currentGroupInfo.groupID);
                router.replace("/new")
            }, 500)

        } catch (e) {
            console.log('e',e)
        };
    },
    postOutGroup: () => {

        OpenIMSDKRN.quitGroup(get().currentGroupInfo.groupID, uuidv4())
            .then(res => {
                setTimeout(() => {
                    get().deleteConversationListById();
                }, 100)
            })
            .catch(err => {
                console.log('err', err);
            })
    },
    setCurrentGroupListFuc: (currentGroupList) => {
        set(() => ({ currentGroupList: [ ...currentGroupList ]  }))
    },
    postGroupInfoFuc: async (type: Number) => {
        const params = {
            groupID: get().currentGroupInfo.groupID,
            needVerification: type,
        };

        OpenIMSDKRN.setGroupInfo(params, uuidv4())
            .then(res => {
                get().getCurrentGroupInfoByReq(get().currentGroupInfo.groupID);
            })
            .catch(err => {
                console.log('errsssss', err);
            })
    },
    postGroupMemberInfoFuc: async (info) => {
        const params = {
            groupID: get().currentGroupInfo.groupID,
           ...info,
        };

        try {
            const data = await OpenIMSDKRN.setGroupMemberInfo(params, uuidv4());

        } catch (e) {
            console.log('e', e);
        };
    },
    deleteConversationListById: async () => {
        const id = get().currentConversation.conversationID;
        OpenIMSDKRN.deleteConversationAndDeleteAllMsg(id, uuidv4())
        const conversationList = get().conversationList;
        const list = [];
        conversationList.forEach((item: any) => {
            if (item.conversationID !== id) {
                list.push(item);
            };
        });
        set(() => ({ conversationList: [...list] }));
        setTimeout(() => {
            router.replace("/new")
        }, 1000)
    },
    kickGroupMember: (menber) => {
        OpenIMSDKRN.kickGroupMember({
            groupID: get().currentGroupInfo.groupID,
            reason: "没有原因",
            userIDList: menber,
        }, uuidv4())
            .then(res => {
                console.log('res', res)
                get().getCurrentGroupMenmberInfoByReq(get().currentGroupInfo.groupID)
                showToast("移除成功");

            })
            .catch(err => {
                console.log('err', err);
            })
    },
}));
